package com.ruicar.afs.cloud.afscase.mq.receiver.processor;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.processor.service.ApproveWorkflowService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessStateInEnum;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.RepealDealDto;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description: 进件端主动撤销
 * @author jiaqi.guo
 * @created 2020/10/15 10:51
 * @version 1.0
 */
@AllArgsConstructor
@Slf4j
@Component
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit",name="enable")
public class RepealDealProcessor implements AfsMqBizProcessor<RepealDealDto> {

   private CaseBaseInfoService caseBaseInfoService;
   private ApproveWorkflowService approveWorkflowService;
   private CaseApproveRecordService caseApproveRecordService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processMessage(RepealDealDto entity) {
        log.info("合作商撤销案件 ==> START : {}", entity);
        if (ObjectUtils.isNotEmpty(entity)) {
            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo, entity.getApplyNo()));
            if (ObjectUtils.isNotEmpty(caseBaseInfo)) {
                String repealMsg = "合作商主动撤销当前案件:" + (StrUtil.isNotBlank(entity.getRepealMsg()) ? entity.getRepealMsg() : "");
                // 存在流程
                if (StrUtil.isNotBlank(entity.getStageId())) {
                    approveWorkflowService.cancelFlow(entity.getStageId(), repealMsg, false);
                } else {
                    // 未发起流程
                    caseApproveRecordService.repeal(entity.getApplyNo(), repealMsg);
                    caseBaseInfo.setBusinessStateIn(AfsEnumUtil.key(BusinessStateInEnum.REPEAL));
                    caseBaseInfoService.updateById(caseBaseInfo);
                }
            }
        }
        log.info("合作商撤销案件 ==> END : {}", entity);
        return true;
    }

    @Override
    public MqTransCode getCode() {
            return MqTransCode.AFS_POS_APPLY_CASE_CTM_APPROVE_CASE_REPEAL_SEND;
    }

}
